package com.kumarn.android.imagesave.full.db;

import com.kumarn.android.imagesave.full.manager.DirectoryManager;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBOpenHelper extends SQLiteOpenHelper {

	// DB name
	static final String DB = "/nailcollection.db";
	// DB version
	static final int DB_VERSION = 1;

	static final String CREATETABLE_GODDS = "CREATE TABLE t_goods ( goods_id    integer primary key autoincrement,"
			+ " goods_name  text,"
			+ " goods_date  integer,"
			+ " goods_image text,"
			+ " goods_memo  text,"
			+ " goods_group integer,"
			+ " goods_url   text);";

	static final String CREATETABLE_GODDS_GROUP = "CREATE TABLE t_goods_group ( goods_group_id integer primary key autoincrement,"
			+ " goods_group_name  text);";

	public DBOpenHelper(Context context) {
		super(context, getDatabasePath(), null, DB_VERSION);
	}

	/**
	 * 初回DB生成時に呼ばれる
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {

		db.beginTransaction(); // トランザクション開始
		try {
			// テーブル生成
			db.execSQL(CREATETABLE_GODDS);
			db.execSQL(CREATETABLE_GODDS_GROUP);

			// 初期データ
			db.execSQL("INSERT INTO t_goods_group(goods_group_name) values('Sample1');");
			db.execSQL("INSERT INTO t_goods_group(goods_group_name) values('Sample2');");
			db.execSQL("INSERT INTO t_goods_group(goods_group_name) values('Sample3');");
			db.execSQL("INSERT INTO t_goods_group(goods_group_name) values('Sample4');");

			db.setTransactionSuccessful(); // コミット
			db.endTransaction(); // トランザクション終了
		} catch (Exception e) {
			Log.d("insertList", "ERROR!!INSERT FAILED");
		}

	}

	/**
	 * DB_VERSIONが変更された場合に呼ばれる
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// テーブル構成が変更になった場合などに移行ロジックを記述
		// ALTER TABLEなど
	}

	/**
	 * DBディレクトリ
	 * @return
	 */
	public static String getDatabasePath() {
		DirectoryManager dm = new DirectoryManager();
		String path = dm.getDatabaseDir().getPath() + DB;
		return path;
	}

}